package com.sailorj.itools.generate;

import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManager;
import com.intellij.openapi.extensions.PluginId;
import com.intellij.openapi.util.io.FileUtil;
import com.sailorj.itools.constants.ParserMapConstants;
import com.sailorj.itools.entity.ParserTable;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class VelocityUtils {

    public static void codeGenerator(ParserTable table, String projectPath) throws Exception {
        // 创建文件对象

        Map<String, Object> map = new HashMap<>();
        map.put("tableInfo", table);
        VelocityContext context = new VelocityContext(map);

        Set<Map.Entry<String, String>> entryseSet = ParserMapConstants.TEMPLATE_MAP.entrySet();
        for (Map.Entry<String, String> entry : entryseSet) {
            System.out.println(entry.getKey()+","+entry.getValue());
            File directory = new File(projectPath + String.format(entry.getKey(), table.getTableName()));
            if (!directory.getParentFile().exists()) {
                directory.getParentFile().mkdirs();
            }
            // 生成什么文件
            PrintWriter pw = new PrintWriter(projectPath + String.format(entry.getKey(), table.getTableName()));
            System.out.println(VelocityUtils.class.getProtectionDomain());
            System.out.println(VelocityUtils.class.getProtectionDomain().getCodeSource());
            System.out.println(VelocityUtils.class.getProtectionDomain().getCodeSource().getLocation());
            // 获取模板
            File file = new File(getPluginPath() + entry.getValue());
            System.out.println(file.exists());
            Template tpl = Velocity.getTemplate(getPluginPath() + entry.getValue(), "UTF-8");
            tpl.merge(context, pw);//将数据context合并入模板tpl中，获得的数据写入sw
            pw.flush();
            pw.close();
        }
    }

    public static String getPluginPath() {
        PluginId pluginId = PluginId.getId("com.sailorj.itools");
        IdeaPluginDescriptor plugin = PluginManager.getPlugin(pluginId);
        File path = plugin.getPath();
        String pluginPath= path.getAbsolutePath();
        return pluginPath + "\\classes\\";
    }
}
